<?php
/**
 * Created by b17
 * 3/5/12 6:07 PM
 */

namespace Managers;

class ProxyCacheManager
{
    /**
     * @var BaseManager
     */
    private $_manager;

    /**
     * @var Cache\ArrayCache
     */
    private $_cache;

    public function __construct(BaseManager $manager)
    {
        $this->_manager = $manager;
        $this->_cache = \Managers\Cache\ArrayCache::getInstance();
    }

    public function __call($name, $args)
    {
        $cacheName = get_class($this->_manager) . ':' . $name . ':' . join('.', $args);
        if ($this->_cache->contains($cacheName)) {
            $res = $this->_cache->fetch($cacheName);
        } else {
            if (method_exists($this->_manager, $name)) {
                $res = call_user_func_array(array($this->_manager, $name), $args);
                $this->_cache->save($cacheName, $res);
            } else {
                throw new \Exception("Method $name does not exist in " . get_class($this->_manager) . ".");
            }
        }
        return $res;
    }

}
